/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package View;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor..
 */

import Shared.*;
import Shared.Server;
import View.MainFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author CCD gruppe 2
 */

public class Login {

    private GUI gui;
    private Server server;
    private String username;
    private boolean state=false;

    public Login(GUI gui,Server server){
        this.gui=gui;
        this.server = server;
        gui.getLoginFrame().getLoginButton().addActionListener(new loginnListener());
    }

    /**
     * A method that tries to log in a user.
     * @throws RemoteException
     */
    public void IsLogedinn() throws RemoteException{
        username = gui.getLoginFrame().getUserNameInput().getText();
        char[] passChar = gui.getLoginFrame().getjPasswordField().getPassword();
        String password = "";
        for(int i=0; i< passChar.length; i++){
            password += ""+passChar[i];
        }
        System.out.println("username " + username + " password " + password);
        if(server.loginn(username, password)) {
            gui.getLoginFrame().setVisible(false);
            gui.getLoginFrame().clearInput();
            gui.getMainFrame().setVisible(true);
            gui.updateProjectList();
            state=true;
        }else{
            gui.getLoginFrame().getErrorMessageLabel().setText("Feil brukernavn/passord!");
            gui.getLoginFrame().getErrorMessageLabel().setVisible(true);
        }
    }

    private class loginnListener implements ActionListener{

        public void actionPerformed(ActionEvent ae) {
            try {
                IsLogedinn();

            } catch (RemoteException ex) {
                Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * A method that returns the login state. Returns true if username and password are correct.
     * @return
     */
    public boolean isState(){
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
        return state;
    }

    /*
     * Getter
     */

    public String getUsername(){
        return username;
    }


}
